package com.simafei.flow.web.util;

import com.simafei.flow.web.common.Weightable;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author fengpengju
 */
public class RouteUtils {

    public static <T extends Weightable> T route(List<T> list) {
        if (list == null || list.isEmpty()) {
            return null;
        }
        int totalWeight = list.stream().mapToInt(Weightable::getWeight).sum();
        int random = ThreadLocalRandom.current().nextInt(totalWeight);
        int current = 0;
        for (T t : list) {
            current += t.getWeight();
            if (random < current) {
                return t;
            }
        }
        return null;
    }
}
